import { useRoute } from "vue-router";
import axios from "axios";
import CryptoJS from "crypto-js";
export default function getUserInfoHook() {
  // 配置地址（wps认证） https://openapi.wps.cn/oauth2/auth?response_type=code&client_id=AK20250825ZXUDTY&scope=kso.user_base.read&state=6faef86f9d5d45df8e32&redirect_uri=http://127.0.0.1:8088
  const getUserInfoFun = async () => {
    const route = useRoute();
    if (route.query.code) {
      // const accessKey = "AK20250825ZXUDTY";
      // const secretKey = "9c5867fcea1ecce0ca2dc4b7aed1b833";
      const accessKey = "AK20251011EOKEIX";
      const secretKey = "192c530a6db79f6245802259e724028f";
      const date = new Date();
      // signature参数
      const Method = "GET";
      const RequestURI = "/v7/users/current";
      const ContentType = "application/json";
      const KsoDate = date.toUTCString();
      // 1. 获取token
      const data = {
        grant_type: "authorization_code",
        client_id: accessKey,
        client_secret: secretKey,
        code: route.query.code,
        redirect_uri: import.meta.env.VITE_API_BACK_URL,
      };
      const headers = {
        "Content-Type": "application/x-www-form-urlencoded",
      };
      const result = await axios({
        url: import.meta.env.VITE_API_WPS_URL + `/oauth2/token`,
        method: "POST",
        data,
        headers: headers,
      });
      // 2. 获取用户信息
      // const RequestBody = ""
      const getKos = () => {
        return (
          "KSO-1 " +
          accessKey +
          ":" +
          CryptoJS.HmacSHA256(
            "KSO-1" + Method + RequestURI + ContentType + KsoDate,
            secretKey
          ).toString()
        );
      };
      const res = await axios({
        url: import.meta.env.VITE_API_WPS_URL + RequestURI,
        method: "GET",
        headers: {
          "Content-Type": ContentType,
          "X-Kso-Date": KsoDate,
          "X-Kso-Authorization": getKos(),
          Authorization: "Bearer " + result.data.access_token,
        },
      });
      if (res.data.code === 0) {
        localStorage.setItem("user_name", res.data.data.ex_user_id);
        return true;
      } else {
        return false;
      }
    } else {
      console.log("地址错误");
    }
  };
  return {
    getUserInfoFun,
  };
}
